package fdoj.eventInvitations.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Person;

public class FbContactsApi extends HttpServlet {

	@EJB
	PersonDao personDao;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession();
			Person loggedUser = (Person) session.getAttribute("loggedUser");
			if (loggedUser != null) {
				String appID = "146344502099847";
				String appSecret = "49df9ba08661e370fcc47c92f829c344";
				String redirectURL = "http://localhost:8080/PozivNaDogadjaj/fbcontactsapi";
				String code = request.getParameter("code");
				if (code != null) {
					String access_token = FacebookAPI.getAccessToken(appID,
							redirectURL, appSecret, code);
					String req = "me/friends?fields=first_name,last_name,email";
					JSONObject object = FacebookAPI.readInfo(access_token, req);
					JSONArray array = (JSONArray) object.get("data");
					HashMap<Integer,Contact> fbContacts = new HashMap<Integer,Contact>();
					Integer id=0;
					for (Object o : array) {
						JSONObject op = (JSONObject) o;
						String email = (String)op.get("email");
						String firstName =(String) op.get("first_name");
						String lastName = (String)op.get("last_name");
						Contact c = new Contact();
						c.setId(id++);
						c.setValid(true);
						c.setEmail(email);
						c.setFirstName(firstName);
						c.setLastName(lastName);
						fbContacts.put(c.getId(),c);
					}
					session.setAttribute("importContacts", fbContacts);
					request.getRequestDispatcher("./importFbContacts.jsp")
							.forward(request, response);
					return;
				}
			}
			else{
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("./index"));
		return;

	}
}
